class Valleyer < ActiveRecord::Base
  has_one :valleyer_logo, :order  => 'created_at desc'
  alias :logo :valleyer_logo
  
  has_many :post_sessions,
    :order => "created_at desc"

  has_many :documet_types,
    :order => "created_at desc"

  has_many :articles,
    :foreign_key => "author_id",
    :order => "created_at desc"

  has_many :reships,
    :foreign_key => "author_id",
    :order => "created_at desc"

  has_many :albums,
    :foreign_key => "author_id",
    :order => "created_at desc"

  has_many :moods

  has_many :browse_records

  # 来访纪录
  has_many :call_in_records,
    :class_name => 'BrowseRecord',
    :foreign_key => :browser_id

  #好友
  has_many :friend_ships

  #好友分组
  has_many :friend_groups

  #好友申请
  has_many :make_friend_requisitions

  validates_presence_of :nick_name
  validates_uniqueness_of :nick_name, :case_sensitive => false
#  validates_numericality_of :start_year, :only_integer => true
  validates_numericality_of :start_year, :end_year, :only_integer => true, :on => :update
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_uniqueness_of :email,:case_sensitive => false
  validates_confirmation_of :password

  
  # nick_name password 验证
  def self.authenticate(nick_name, password)
#    logger.debug("#{nick_name}'s password [#{Base64.encode64(password).chop}] checking...")
    find_by_nick_name_and_password(nick_name,
      Base64.encode64(password).chop)
  end

  # 当前登录的valleyer
  def self.current_valleyer
    Thread.current[:current_valleyer_id] ? find(Thread.current[:current_valleyer_id]) : nil
  end

  def self.current_valleyer_id
    Thread.current[:current_valleyer_id]
  end

  def check_password(other_password)
    Base64.encode64(other_password).chop == password
  end

  # 安全key存储在cookies
  def security_key_in_cookies
    Digest::SHA1.hexdigest(id.to_s + personal_key)
  end

  def check_security_key_in_cookies(sk)
    security_key_in_cookies == sk
  end

  # 原密码
  def source_password
    decode_password
  end

  def before_create
    self.personal_key = ActiveSupport::SecureRandom.hex(12)
  end

  def before_save
    encode_password if password_changed?
  end

  #当前被访问者的最新心情
  def latest_mood
    Mood.find(:first, :conditions => ["valleyer_id = ?", id], :order => "created_at desc")
  end

  #取规定条数的日志
  def numerary_articles(args = {:last => 3})
    Article.find(:all, :limit => args[:last], :conditions => ["author_id = ?", id], :order => "created_at desc")
  end

  #转载
  def numerary_reships(args = {:last => 3})
    Reship.find(:all, :limit => args[:last], :conditions => ["author_id = ?", id], :order => "created_at desc")
  end

  # 主页访客
  def clients( args = { :last => 10 })
    Valleyer.all :select => 'disnict valleyers.*',
      :conditions => [
        'browse_records.valleyer_id = ? ',
        id
      ],
      :include => :call_in_records,
      :order => 'browse_records.created_at desc',
      :limit => args[:last]
  end

  # 相册访客
  def clients_to_albums(args = { :last => 10 })
    Valleyer.all :select => 'disnict valleyers.*',
      :conditions => [
        'browse_records.valleyer_id = ? and browse_records.album_id is not null',
        id
      ],
      :include => :call_in_records,
      :order => 'browse_records.created_at desc',
      :limit => args[:last]
  end

  def browse_record(client)
    BrowseRecord.find_by_browser_id(client.id, :order => 'created_at desc')
  end

  #我的好友
  def all_of_my_friends
    FriendShip.find_all_by_valleyer_id(id).each_with_object([]) do |f,fs|
      fs << f.friend
    end
  end

  #根据条件查询我的好友
  def all_friends_by_term(args = {})
    FriendShip.all(:conditions => [
      "valleyers.nick_name like ? and valleyers.sex like ? and valleyer_id = ?",
      "%" + args[:nick_name] + "%",
      args[:sex],
      id
    ],:include => :friend
    ).each_with_object([]) do |f,fs|
      fs << f.friend
    end
  end

  #根据条件查询所有的谷友
  def all_with_out_my_friends(args = {})
    Valleyer.all :conditions => [
      "nick_name like ? and sex like ? and id != ?",
      "%" + args[:nick_name] + "%",
      args[:sex],
      id
    ]
  end

  #该谷友是否是我的好友
  def is_my_friend?(valleyer_id)
    if FriendShip.first :conditions => ["valleyer_id = ? and friend_id = ?", valleyer_id, id]
      return false
    else
      return true
    end
  end

  #活跃会员
  def self.all_rather_new_member(args = {:last => 12})
    Valleyer.all :order => "actived_at desc",
      :limit => args[:last]
  end

  #新进会员
  def self.all_new_entrants_member(args = {:last => 12})
    Valleyer.all :order => "created_at desc",
      :limit => args[:last]
  end

  # 有交友申请吗？
  def any_new_friend_apply?
    new_friend_applies.any?
  end

  def new_friend_applies
	WaitMakeFriendRequisition.wait_me_to_confirm(id)
  end

  #最新相册
  def the_new_albums(args = {:last => 2})
    Album.find_all_by_author_id id,
      :order => "created_at desc",
      :limit => args[:last]
  end

  def actived_at!
    self.actived_at = Time.now
    save(false)
  end

  private
  # 加密密码
  def encode_password
    self.password = Base64.encode64(password).chop
  end

  def decode_password
    Base64.decode64(password)
  end
end
